<?php
namespace app\admin\controller;
use think\Request;
use think\Db;
use think\Config;

class SupplierGoods extends Base
{

	/**
	 * 商品管理
	 * @return [type] [description]
	 */
	public function index()
	{
		$param = request()->param();
		$keywords = $param['keywords'];
		$cate_id = $param['cate_id'];
		$supplier_id =$param['supplierid'];
		if(!$supplier_id) {$this->error('参数错误');}

		$category = Db::name('goods_category')->where(['cate_status'=>1])->select();
		$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');

		$query = Db::table('sdzx_goods')->field('g.*,max(sval.price) as max_price,min(sval.price) as min_price,sum(sval.sales) as sales,max(sval.status) as status,min(sval.sellout) as sellout,b.brand_name')->alias('g')
		->join('sdzx_goods_specval sval','g.goods_id=sval.goods_id and sval.specval_pid!=0')
		->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
		->where("sval.supplier_id={$supplier_id}")
		->order('g.goods_id desc')
		->group('g.goods_id');
		if ($keywords) {
			$query->where(" goods_name like '%{$keywords}%' or b.brand_name like '%{$keywords}%' ");
		}
		if ($cate_id) {
			$w_cateId = implode(',',array_column($cat->getChildren($cate_id,$category),'cate_id'));
			$query->where("g.category_id in({$w_cateId})");
		}
		$list=$query->order('sort desc, goods_id asc')->paginate('',false,['query'=>Request()->param()]);
		foreach ($list as $k => $v) {
			$v['specval'] = Db::connect([],'sval')->field('*')
			->name('goods_specval')->where(['goods_id'=>$v['goods_id'],'supplier_id'=>$supplier_id])->order('sort desc')->select();
			$list[$k] = $v;
		}

		$supplier = Db::name('supplier')->where('supplier_id',$supplier_id)->find();
		return $this->fetch('',['list'=>$list,'catelist'=>$cat->getList(0,$category),'supplier'=>$supplier]);
	}

	/**
	 * 规格状态
	 * @return [type] [description]
	 */
	function specvalState(){
		$specval_id = Request()->param('specval_id');
		$status = Request()->param('status');
		$goods_id = Request()->param('goods_id');
		$ishot = Request()->param('ishot');
		$isrecommend = Request()->param('isrecommend');
		$sellout = Request()->param('sellout');
		if (empty($goods_id)) {
			$this->error('参数错误');
		}
		if (empty($specval_id)) {
			$this->error('参数错误');
		}
		$data=[];
		if ($status!=null) {
			$data['status']=$status;
		}
		if ($ishot!=null) {
			$data['is_hot']=$ishot;
		}
		if ($isrecommend!=null) {
			$data['is_recommend']=$isrecommend;
		}
		if ($sellout!=null) {
			$data['sellout']=$sellout;
		}
		$re = Db::name('goods_specval')->where(['specval_id'=>$specval_id])->update($data);
		if ($re!==false) {
			$tmp = Db::field('max(status) as status,max(is_hot) as is_hot,max(is_recommend) as is_recommend,min(sellout) as sellout')
			->name('goods_specval')
			->where(['goods_id'=>$goods_id])
			->group('goods_id')->find();
			$Refresh = '';
			if (($ishot!=null && $tmp['is_hot']<=0) || ($status!=null && $tmp['status']<=0) || ($isrecommend!=null && $tmp['is_recommend']<=0) ||($sellout!=null && $tmp['sellout']==1) ) {
				$Refresh='refresh';
			}
			if ($status!=null) {
				$this->success('操作成功',$Refresh,['status'=>$status]);
			}
			if ($ishot!=null) {
				$this->success('操作成功',$Refresh,['status'=>$ishot]);
			}
			if ($isrecommend!=null) {
				$this->success('操作成功',$Refresh,['status'=>$isrecommend]);
			}
			if ($sellout!=null) {
				$this->success('操作成功',$Refresh,['status'=>$sellout]);
			}
		}else{
			$this->error('操作失败');
		}
	}

	function selectgoods(){
		$param = request()->param();
		$keywords = $param['keywords'];
		$cate_id = $param['cate_id'];
		$supplier_id =$param['supplierid'];
		if(!$supplier_id) {$this->error('参数错误');}

		$category = Db::name('goods_category')->where(['cate_status'=>1])->select();
		$cat = CAT('goods_category',array('cate_id','cate_pid','cate_name','fullname'),'cate_status=1');

		$query = Db::table('sdzx_goods')->field('g.*,b.brand_name')->alias('g')
		->join('sdzx_goods_brand b','g.brand_id=b.brand_id','left')
		->order('g.goods_id desc');
		if ($keywords) {
			$query->where(" goods_name like '%{$keywords}%' or b.brand_name like '%{$keywords}%'");
		}
		if ($cate_id) {
			$w_cateId = implode(',',array_column($cat->getChildren($cate_id,$category),'cate_id'));
			$query->where("g.category_id in({$w_cateId})");
		}
		$list=$query->order('sort desc, goods_id asc')->paginate('',false,['query'=>Request()->param()]);

		$supplier = Db::name('supplier')->where('supplier_id',$supplier_id)->find();
		return $this->fetch('',['list'=>$list,'catelist'=>$cat->getList(0,$category),'supplier'=>$supplier]);
	}

	function addgoods(){
		$param = request()->param();
		if (request()->isPost()) {
			$sval = $param['sval'];
			$supplier_id = $param['supplierid'];

			Db::startTrans();
			foreach ($sval as $k => $v) {
				$tmp = Db::name('goods_specval')->where(['specval_id'=>$v['specval_id']])->find();
				if (empty($tmp['specval_pid'])) { 
					if($v['check'] == 'true'){
						$tmp['price'] = $v['price'];
						$tmp['unit_price'] = $v['price']/$tmp['specvalnum'];
						$tmp['stock'] = 0;
						$tmp['sales'] = 0;
						$tmp['purchase_price'] = 0;
						$tmp['supplier_id'] = $supplier_id;
						$tmp['create_date'] = date('Y-m-d H:i:s');
						$tmp['sellout'] = 0;
						$tmp['specval_pid'] = $tmp['specval_id'];

						unset($tmp['specval_id']);
						$re = Db::name('goods_specval')->insertGetId($tmp);
						if (!$re) {
							Db::rollback();
							$this->error('操作失败');
						}
					}
				}else{
					$re = Db::name('goods_specval')->where(['specval_id'=>$v['specval_id']])->update([
						'price' => $v['price'],
						'unit_price' => ['exp',$v['price'].'/specvalnum'],
						'status' => ($v['check']=='true')?1:0
					]);
					if ($re===false) {
						Db::rollback();
						$this->error('操作失败');
					}
				}
			}

			Db::commit();
			$this->success('操作成功','');
		}else{
			
			$goods = Db::name('goods')->where('goods_id',$param['goodsid'])->find();
			$sval = Db::name('goods_specval')->where("specval_pid = 0 and goods_id = {$param['goodsid']}")->select();

			foreach ($sval as $k => $v) {
				$has = Db::name('goods_specval')->where(['specval_pid'=>$v['specval_id'],'supplier_id'=>$param['supplierid']])->find();
				if ($has) {
					$sval[$k] = $has;
					if ($has['status']) {
						$sval[$k]['checked'] = true;
					}else{
						$sval[$k]['checked'] = false;
					}
				}else{
					$sval[$k]['checked'] = false;
				}
			}
			$supplier = Db::name('supplier')->where('supplier_id',$param['supplierid'])->find();
			$data['goods'] = $goods;
			$data['sval'] = $sval;
			$data['supplier'] = $supplier;
			return $this->fetch('',$data);
		}
	}

	/**
	 * 删除规格
	 * @return [type] [description]
	 */
	function delspecval(){
		$ids = Request()->param('ids');
		if (empty($ids)) {
			$this->error('参数错误');
		}

		$has = Db::field('o.order_id,og.goods_specval_name')
		->table('sdzx_order')->alias('o')
		->join('sdzx_order_goods og','o.order_id=og.order_id')
		->where("(o.order_status=20 or o.order_status=25 or o.order_status=30 or o.order_status=40 )and og.goods_specval_id in ({$ids})")
		->find();
		if ($has) {
			$this->error('规格【'.$has['goods_specval_name'].'|'.$has['order_id'].'】使用中不能删除','');
		}

		Db::name('goods_specval')->where(['specval_id'=>['in',$ids]])->delete();
		$this->success('删除成功','');
	}
}